package com.aiden.app.common.util

import android.app.Activity
import android.app.Dialog
import android.content.DialogInterface
import android.graphics.drawable.BitmapDrawable
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.Editable
import android.text.TextWatcher
import android.view.*
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toolbar
import com.aiden.app.common.R
import com.aiden.app.common.base.BaseRecyclerViewAdapter
import com.aiden.app.common.extension.color
import com.aiden.app.common.extension.isNil
import com.yanzhenjie.recyclerview.widget.DefaultItemDecoration


/**
 * 选择图片对话框（选择相机或者相册）
 *
 * @author yanggeng
 * @date 2018/11/20 下午3:34
 */
class BottomDialog {

    private var dialog: Dialog? = null
    private var onUserSelectListener: OnUserSelectListener? = null
    private var onItemSelectListener: OnItemSelectListener? = null
    private lateinit var activity: Activity

    constructor(activity: Activity, text0: String, text1: String, cancel: String) {
        this.activity = activity
        val view = LayoutInflater.from(activity).inflate(R.layout.layout_bottom_dialog, null)
        val tvText1 = view.findViewById<TextView>(R.id.tv_text1)
        tvText1.text = text0
        val tvText2 = view.findViewById<TextView>(R.id.tv_text2)
        tvText2.text = text1
        tvText1.setOnClickListener {
            if (onItemSelectListener != null) {
                onItemSelectListener?.onItemClick(0)
            } else {
                LogUtils.e(TAG, "Please set OnUserSelectListener!!!")
            }
        }
        tvText2.setOnClickListener {
            if (onItemSelectListener != null) {
                onItemSelectListener?.onItemClick(1)
            } else {
                LogUtils.e(TAG, "Please set OnItemSelectListener!!!")
            }
        }
        val tvCancel = view.findViewById<TextView>(R.id.tv_cancel)
        tvCancel.text = cancel
        tvCancel.setOnClickListener {
            if (onItemSelectListener != null) {
                onItemSelectListener?.onItemClick(2)
            } else {
                LogUtils.e(TAG, "Please set OnItemSelectListener!!!")
            }
        }

        dialog = Dialog(activity, R.style.TransparentDialog)
        dialog?.setContentView(view, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))

        val window = dialog?.window
        window?.setWindowAnimations(R.style.popup_window_bottom)
        window?.setGravity(Gravity.BOTTOM)
//        window?.setBackgroundDrawable(BitmapDrawable())
        val lp = window?.attributes!!

        lp.width = Toolbar.LayoutParams.MATCH_PARENT
        lp.height = Toolbar.LayoutParams.WRAP_CONTENT

        dialog?.onWindowAttributesChanged(lp)
        dialog?.setCanceledOnTouchOutside(true)
    }

    constructor(activity: Activity, contentView: View, layoutParams: ViewGroup.LayoutParams) {
        dialog = Dialog(activity, R.style.TransparentDialog)
        dialog?.setContentView(contentView, layoutParams)

        val window = dialog?.window!!
        window.setWindowAnimations(R.style.popup_window_bottom)
        window.setBackgroundDrawable(BitmapDrawable())
        val lp = window.attributes

        lp.x = 0
        lp.y = activity.windowManager.defaultDisplay.height
        lp.width = Toolbar.LayoutParams.MATCH_PARENT
        lp.height = Toolbar.LayoutParams.WRAP_CONTENT
        dialog?.onWindowAttributesChanged(lp)
        dialog?.setCanceledOnTouchOutside(true)
    }

    constructor(activity: Activity, onEditCompletedListener: OnEditCompletedListener) {
        val view = LayoutInflater.from(activity).inflate(R.layout.layout_comment, null)
        val etComment = view.findViewById<EditText>(R.id.et_comment)
        val tvSend = view.findViewById<TextView>(R.id.tv_send)
        etComment.addTextChangedListener(object : TextWatcher {
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
//                tvSend.isEnabled = s?.toString()?.trim()?.isNotEmpty()!!
                tvSend.isEnabled = !s?.toString()?.trim().isNil()
            }
        })
        tvSend.setOnClickListener {
            onEditCompletedListener.onEditCompleted(etComment.text.toString())
        }
        dialog = Dialog(activity, R.style.CommentDialog)
        dialog?.setContentView(view, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))

        val window = dialog?.window!!
        window.setWindowAnimations(R.style.popup_window_bottom)
        window.setBackgroundDrawable(BitmapDrawable())
        window.setGravity(Gravity.BOTTOM)
        val lp = window.attributes

        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        window.attributes = lp
        dialog?.setCanceledOnTouchOutside(true)
        dialog?.setOnKeyListener { dialog1, keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                dialog?.dismiss()
                return@setOnKeyListener false
            } else if (keyCode == KeyEvent.KEYCODE_DEL || keyCode == KeyEvent.KEYCODE_ENTER) {
                return@setOnKeyListener false
            }
            true
        }
    }

    constructor(activity: Activity, onInputListener: OnInputListener) {
        val mKeys = arrayListOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "", "0", "<-")
        val view = LayoutInflater.from(activity).inflate(R.layout.layout_number_keyboard, null)
        val rvKeyBoard = view.findViewById<RecyclerView>(R.id.recycler_view)
        rvKeyBoard.layoutManager = GridLayoutManager(activity, 3)
        val adapter = BaseRecyclerViewAdapter(activity, mKeys, R.layout.layout_simple_button_item) { child, key, position ->
            val tvItem = child.findViewById<TextView>(R.id.tv_item)
            tvItem.text = key
            if (position == 9 || position == 11) {
                tvItem.setBackgroundColor(activity.color(R.color.color_gray_ee))
            } else {
                tvItem.setBackgroundResource(R.drawable.selector_rl_background)
            }
        }
        val mInputKeys = StringBuilder()
        adapter.setOnItemClickListener(object : BaseRecyclerViewAdapter.OnItemClickListener {
            override fun onItemClick(v: View, position: Int) {
                when (position) {
                    0, 1, 2, 3, 4, 5, 6, 7, 8, 10 -> {
                        if (mInputKeys.length < 6) {
                            if (mInputKeys.length == 1 && mInputKeys.toString() == "0") {
                                if (position != 10) {
                                    mInputKeys.deleteCharAt(0)
                                    mInputKeys.append(mKeys[position])
                                }
                            } else {
                                mInputKeys.append(mKeys[position])
                            }
                            onInputListener.onInput(mInputKeys.toString())
                        }
                    }
                    11 -> {
                        if (mInputKeys.isNotEmpty()) {
                            mInputKeys.deleteCharAt(mInputKeys.length - 1)
                            onInputListener.onInput(mInputKeys.toString())
                        }
                    }
                }
            }
        })
        rvKeyBoard.adapter = adapter
        rvKeyBoard.addItemDecoration(DefaultItemDecoration(activity.color(R.color.color_gray_ee)))
        view.findViewById<Button>(R.id.btn_cancel).setOnClickListener {
            dialog?.cancel()
            mInputKeys.delete(0, mInputKeys.length)
        }
        view.findViewById<Button>(R.id.btn_confirm).setOnClickListener {
            dialog?.dismiss()
            onInputListener.onInput(mInputKeys.toString())
            mInputKeys.delete(0, mInputKeys.length)
        }
        dialog = Dialog(activity, R.style.DimFalseDialog)
        dialog?.setContentView(view, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))

        val window = dialog?.window!!
        window.setWindowAnimations(R.style.popup_window_bottom)
        window.setBackgroundDrawable(BitmapDrawable())
        window.setGravity(Gravity.BOTTOM)
        val lp = window.attributes

        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        window.attributes = lp
        dialog?.setCanceledOnTouchOutside(true)
        dialog?.setOnKeyListener { dialog1, keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                dialog?.dismiss()
                return@setOnKeyListener false
            } else if (keyCode == KeyEvent.KEYCODE_DEL || keyCode == KeyEvent.KEYCODE_ENTER) {
                return@setOnKeyListener false
            }
            true
        }
        dialog?.setOnCancelListener {
            onInputListener.onInput("")
        }
    }

    fun setOnKeyListener(onKeyListener: DialogInterface.OnKeyListener) {
        dialog?.setOnKeyListener(onKeyListener)
    }

    fun show() {
        if (dialog != null) {
            dialog?.show()
        }
    }

    fun isShowing(): Boolean {
        return dialog?.isShowing!!
    }

    fun dismiss() {
        if (dialog != null && dialog?.isShowing!!) {
            dialog?.dismiss()
        }
    }

    fun setOnUserSelectListener(onUserSelectListener: OnUserSelectListener) {
        this.onUserSelectListener = onUserSelectListener
    }

    fun setOnItemSelectListener(onItemSelectListener: OnItemSelectListener) {
        this.onItemSelectListener = onItemSelectListener
    }

    fun setOnDismissListener(onDismissListener: DialogInterface.OnDismissListener) {
        dialog?.setOnDismissListener(onDismissListener)
    }

    interface OnUserSelectListener {

        fun camera()

        fun album()

        fun cancel()
    }

    interface OnItemSelectListener {
        fun onItemClick(position: Int)
    }

    companion object {

        private val TAG = "BottomSelectDialog"

        val SHARE_TO_TIMELINE = 0
        val SHARE_TO_WECHAT_FRIEND = 1
        val SHARE_TO_QQ_FRIEND = 2
        val SHARE_TO_QQ_ZONE = 3
        val SHARE_TO_WEIBO = 4
        val SHARE_MORE = 5
        val COPY = 6
        val COLLECT = 7
        val REPORT = 8
    }

    interface OnEditCompletedListener {
        fun onEditCompleted(text: String)
    }

    interface OnInputListener {
        fun onInput(input: String)
    }
}
